package labox.innovation.gameserver.model.actor.instance;

import java.util.StringTokenizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import labox.innovation.config.Config;
import labox.innovation.gameserver.datatables.Repair;
import labox.innovation.gameserver.model.L2ItemInstance;
import labox.innovation.gameserver.network.SystemMessageId;
import labox.innovation.gameserver.network.serverpackets.ActionFailed;
import labox.innovation.gameserver.network.serverpackets.InventoryAndMerchantPakcet;
import labox.innovation.gameserver.network.serverpackets.NpcHtmlMessage;
import labox.innovation.gameserver.network.serverpackets.SystemMessage;
import labox.innovation.gameserver.templates.chars.NpcTemplate;
import labox.innovation.gameserver.templates.item.FuzeEconomicManager.OPSTATE;

/**
 * 修理师NPC
 * @author Frank
 *
 */
public class FuzeRepairerInstance extends FuzeNpcInstance{
	
	private static final Logger _log = LoggerFactory.getLogger(FuzeRepairerInstance.class.getName());
	
	public FuzeRepairerInstance(long objectId, NpcTemplate template) {
		super(objectId, template);
	}
	
	/**
	 * 下发背包中信息
	 * @param player
	 */
	private void showInventoryWindow(FuzePcInstance player) {
		float storeBuyRate = player.getTemplate().getBaseShopBuyRate();  //-- 商店购买系数
		float storeSellRate = player.getTemplate().getBaseShopSellRate();  //-- 商店出售系数
		int karma = player.getKarma();  //-- 获取当前玩家身上的善恶值
		
		if (karma >= Config.KARMAREDSSET) {
			storeBuyRate = (float)(Config.KARMABASE + karma)/Config.KARMABASE;
			storeSellRate = (float)(Config.KARMABASE - karma)/Config.KARMABASE;
		}
		
		player.sendPacket(ActionFailed.STATIC_PACKET);
		player.sendPacket(new InventoryAndMerchantPakcet(player, getNpcId(), storeBuyRate, storeSellRate));
		return;
	}
	
	/**
	 * 
	 */
	@Override
	public void onBypassFeedback(FuzePcInstance player, String command) {
		if (command.startsWith("repair")) {  //-- NPC修理功能
			int price = 0;
			StringTokenizer st = new StringTokenizer(command, " ");
			st.nextToken(); // Get actual command
			price = Integer.parseInt(st.nextToken());
			doRepair(player, price);
		} else if (command.startsWith("GetMerchantList")) {  //-- NPC买卖功能
			showInventoryWindow(player);
		}
		
		super.onBypassFeedback(player, command);		
	}
	
	/**
	 * 获取维修玩家装备所需银文数
	 * @return
	 */
	private static int getRepairCost(FuzePcInstance player) {
		float result = 0.0F;
		int level = 0;
//		int levelRate = Integer.parseInt(Repair.getInstance().getValueByKey("LevelRate"));
		int levelRate = 0;
		float gradeRate = 1.0F;
		float shopRepairRate = player.getTemplate().getBaseShopRepairRate();
		int karma = player.getKarma();  //-- 获取当前玩家身上的善恶值
		
		if (karma >= Config.KARMAREDSSET) {
			shopRepairRate = (float)(Config.KARMABASE + karma)/Config.KARMABASE;
		}
			
		int enduranceUp =0;
		int Endurance = 0;
		String[] gradeArray = {"Talisman", "BaoDevice", "LingDevice", "Treasure", "Horl"};
		String itemGrade;
		L2ItemInstance[] items = player.getInventory().getAllEquipItems();  //-- 获取玩家装备列表
		
		if (items != null) {
			for (int i = 0; i < items.length; i++) {
				if (items[i] == null)
					continue;
				if (items[i].canRepair()) {  //-- 判断是否可修理
					level = items[i].getItemLvl();			
					
//					if (level <= 20)
//						levelRate = Integer.parseInt(Repair.getInstance().getValueByKey("LowLevel"));
//					else
//						levelRate = Integer.parseInt(Repair.getInstance().getValueByKey("HighLevel"));
					
					itemGrade = gradeArray[items[i].getItemGrade()];
					gradeRate = Float.parseFloat(Repair.getInstance().getValueByKey(itemGrade));
					levelRate = level * 3 + 30;
//					result = result + (level * levelRate * gradeRate * shopRepairRate);

					enduranceUp = items[i].getEnduranceUp();
					Endurance = items[i].getEndurance();
					if (items[i].getEnduranceUp() > 0)
						result = result + (levelRate * gradeRate * shopRepairRate) * ((enduranceUp * (enduranceUp - Endurance)) / (float)(2500 * enduranceUp));
//						result = result + (levelRate * gradeRate * shopRepairRate) * ((float)(items[i].getEnduranceUp() / 1000) * (1 - (float)items[i].getEndurance() / items[i].getEnduranceUp()));
					else
						result = result + (levelRate * gradeRate * shopRepairRate);
				}
			}
		}

		return (int)Math.ceil(result);
	}
	
	/**
	 * 修理
	 * @param player
	 * @param price
	 */
	private void doRepair(FuzePcInstance player, int price) {
		boolean isRepaired = true;
		
		if (!player.getInventory().hasEnoughSilverMoney(OPSTATE.REPAIR.getValue(), player, price)) {  //-- 没有足够的银文修理装备
			player.sendPacket(new SystemMessage(SystemMessageId.YOU_NOT_ENOUGH_ADENA));			
			return;
		}
		
		L2ItemInstance[] items = player.getInventory().getAllEquipItems();  //-- 获取玩家装备列表
		try {
			if (items != null) {
				for (int i = 0; i < items.length; i++) {
					if (items[i] == null)
						continue;
					
					if (items[i].canRepair()) {  //-- 判断是否可修理
						items[i].setEndurance(items[i].getEnduranceUp());  //-- 重新设置玩家装备耐久度为最大
					}
				}
			}
		} catch (Exception e) {
			_log.error("NPC修理执行修理动作时出错", Config.SERVER_ID, e);
			isRepaired = false;
		}
		
		if (isRepaired && (player.reduceMoneySilver(OPSTATE.REPAIR.getValue(), price, this, true))) {
			if (price > 0)
			    player.sendPacket(new SystemMessage(SystemMessageId.NPC_REPAIR_RESULT_OK));
			else
				player.sendPacket(new SystemMessage(SystemMessageId.NPC_REPAIR_RESULT_IGNORE));
		}
		
		player.sendPacket(ActionFailed.STATIC_PACKET);
		
		return;
	}
	
	/**
	 * 修理对外接口
	 * @param player
	 */
	public static void doRepair(FuzePcInstance player) {
		int price = getRepairCost(player);
        boolean isRepaired = true;
		
		if (player.getMoneySilver() + player.getMoneyNote() < price) {  //-- 没有足够的银文修理装备
//			player.sendPacket(new SystemMessage(SystemMessageId.NOT_ENOUGH_MONEY_NOTE));			
			return;
		}
		
		L2ItemInstance[] items = player.getInventory().getAllEquipItems();  //-- 获取玩家装备列表
		try {
			if (items != null) {
				for (int i = 0; i < items.length; i++) {
					if (items[i] == null)
						continue;
					
					if (items[i].canRepair()) {  //-- 判断是否可修理
						items[i].setEndurance(items[i].getEnduranceUp());  //-- 重新设置玩家装备耐久度为最大
					}
				}
			}
		} catch (Exception e) {
			_log.error("NPC修理执行修理动作时出错", Config.SERVER_ID, e);
			isRepaired = false;
		}
		
		if (isRepaired && (player.reduceMoneySilver(OPSTATE.REPAIR.getValue(), price, null, false))) {
			if (price > 0)
			    player.sendMessage("自动修理装备，消耗银文" + String.valueOf(price));
//			if (price > 0)
//			    player.sendPacket(new SystemMessage(SystemMessageId.NPC_REPAIR_RESULT_OK));
//			else
//				player.sendPacket(new SystemMessage(SystemMessageId.NPC_REPAIR_RESULT_IGNORE));
		}
		
		player.sendPacket(ActionFailed.STATIC_PACKET);
	}
	
	/**
	 * 判断是否需要修理
	 * @param player
	 * @return
	 */
	private boolean isNeedRepair(FuzePcInstance player) {
		boolean result = false;
		L2ItemInstance[] items = player.getInventory().getAllEquipItems();  //-- 获取玩家装备列表
		try {
			if (items != null) {
				for (int i = 0; i < items.length; i++) {
					if (items[i] == null)
						continue;
					
					if (items[i].canRepair() && (items[i].getEndurance() < items[i].getEnduranceUp())) {  //-- 判断是否可修理
						result = true;
						break;
					}
				}
			}
		} catch (Exception e) {
			_log.error("NPC修理执行判断是否需要修理逻辑时出错", Config.SERVER_ID, e);
			result = false;
		}
		
		return result;
	}
	
	@Override
	public void showChatWindow(FuzePcInstance player, int val) {
		int cost = 0;
		
		if (isNeedRepair(player)) {
			if (val <=0) {
				cost = getRepairCost(player); 
			}
		}

		int npcId = getTemplate()._id;

		String filename;
		switch (npcId) {
		default:
			// Get the text of the selected HTML file in function of the npcId and of the page number
			filename = (getHtmlPath(npcId, val));
			break;
		}

		// Send a Server->Client NpcHtmlMessage containing the text of the L2NpcInstance to the L2PcInstance 
		NpcHtmlMessage html = new NpcHtmlMessage(getObjectId());
		html.setFile(filename);

		html.replace("%objectId%", String.valueOf(getObjectId()));
		html.replace("%cost%", String.valueOf(cost));
		player.sendPacket(html);

		// Send a Server->Client ActionFailed to the L2PcInstance in order to avoid that the client wait another packet
		player.sendPacket(ActionFailed.STATIC_PACKET);
		
	}
}
